package org.budo.jedis.pool.factory;

import org.budo.jedis.pool.BudoJedisPool;

import redis.clients.jedis.JedisPoolConfig;

/**
 * @author lmw
 */
public class BudoJedisPoolFactory extends AbstractBudoJedisPoolFactory {
    @Override
    public BudoJedisPool getObject() throws Exception {
        if (null == this.getHost() || this.getHost().trim().isEmpty()) {
            throw new IllegalArgumentException("#12 host is required, host=" + this.getHost() + ", this=" + this);
        }

        JedisPoolConfig jedisPoolConfig = this.getJedisPoolConfig();
        if (null == jedisPoolConfig) {
            jedisPoolConfig = this.defaultJedisPoolConfig();
        }

        return new BudoJedisPool(jedisPoolConfig, //
                this.getHost(), //
                this.getPort(), //
                this.getTimeout(), //
                this.getPassword(), //
                this.getDatabase());
    }

    private JedisPoolConfig defaultJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

        jedisPoolConfig.setMaxTotal(500); // 最大实例总数

        jedisPoolConfig.setMinIdle(1); // 最小空闲数
        jedisPoolConfig.setMaxIdle(9); // 最大空闲数

        jedisPoolConfig.setMaxWaitMillis(5000); // 获取链接最长等待时间

        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestWhileIdle(true);

        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30 * 1000);

        return jedisPoolConfig;
    }
}